//
//  PdcDetailVC.m
//  夺宝吧
//
//  Created by xiaocai on 15/6/30.
//  Copyright (c) 2015年 FangYuan. All rights reserved.
//

#import "PdcDetailVC.h"
#import "DetailCell.h"
#import "RecordModel.h"
#import "BuyNowBottom.h"
#import "BuyGoOnBottom.h"
#import "JSBadgeView.h"
#import "GoToBottom.h"
#import "MJRefresh.h"
//参与记录
#define RECORD_URL @"/api/ApiGoods/getShoppingList"
//商品详情
#define DETAIL_URL @"/api/ApiGoods/getGoodsDetail"
@interface PdcDetailVC ()<UITableViewDataSource,UITableViewDelegate>
{
    //所有参与记录列表
    UITableView *_tableView;
    //数据源
    NSMutableArray *_data;
    //表头
    DetailHeader *_header;
    //商品详情类别
    DetailType _detailType;
    //当前页
    NSInteger _currentPage;
    //购物车图标
    UIButton *_carImg;
    //圆角通知
    JSBadgeView *badgeView;
    NSString *_goodsId;
    //首次加hud标志
    BOOL isFirstFlag;
    
    //用于显示最后一页
    UILabel *_footer;
    
    GoToBottom *bottom;
}

@property (nonatomic , strong) NSMutableArray *historyData;

@end

@implementation PdcDetailVC
- (void)viewWillAppear:(BOOL)animated
{
    if (isFirstFlag == NO) {
//        [WYPublic addHudToWindow];
    }
    isFirstFlag = YES;
}
- (void)viewDidLoad {
    [super viewDidLoad];
//    [WYPublic addHudToWindow];
    // Do any additional setup after loading the view.
    self.automaticallyAdjustsScrollViewInsets = NO;
    _currentPage = 1;
    _data = [NSMutableArray array];
    self.historyData = [NSMutableArray array];
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"Dbb_backColor"]];
    [self loadCustomNaviBar];
    [self loadTableView];
    //获取商品详情
    [self requestForDetail];
}

//获取商品详情接口
- (void)requestForDetail
{
    NSDictionary *params = @{@"id":[WYPublic getUsefullStr:self.pdc_id]};
    if (self.isSidFlag) {
        if ([UserInfo isUserLogin]) {
            params = @{@"id":self.pdc_id,@"is_sid":@"1",@"uid":[UserInfo getUserID]};
        }else{
            params = @{@"id":self.pdc_id,@"is_sid":@"1"};
        }
    }else{
        if ([UserInfo getUserID]!=nil) {
            params = @{@"id":self.pdc_id,@"uid":[UserInfo getUserID]};
        }
    }
    [WYPublic addHudToWindow];
    self.view.userInteractionEnabled = NO;
    [WYRequest startPostForDicWithUrlStR:[NSString stringWithFormat:@"%@%@",DBB_IP,DETAIL_URL] Parameters:params successBlock:^(NSDictionary *dic) {
        
        @synchronized(self) {
            
            NSNumber *ret = dic[@"ret"];
            if ([ret intValue] != 0) {
                [WYPublic removeHudToWindow];
                return ;
            }
            
            NSDictionary *pdc = dic[@"data"];
            int has_bought = [pdc[@"has_bought"] intValue];
            NSNumber *status = pdc[@"status"];
            //购物车显示加一
            WYShopCarModel *car_model = [[WYShopCarModel alloc]init];
            //过期标志
            NSNumber *flagNum = pdc[@"is_sold_out"];
            //期数
            NSString *qishu = pdc[@"goods"][@"qishu"];
            _goodsId = pdc[@"goods"][@"id"];
            NSString *maxqishu = pdc[@"goods"][@"maxqishu"];
            car_model.car_id = self.pdc_id;
            car_model.car_new_id = pdc[@"goods"][@"sid"];
            car_model.imgPath = pdc[@"goods"][@"thumb_url"];
            car_model.name = pdc[@"goods"][@"title"];
            car_model.all_need = pdc[@"goods"][@"zongrenshu"];
            car_model.left_need = pdc[@"goods"][@"shenyurenshu"];
            
            
            switch ([status intValue]) {
                case 1:
                {
                    //已经购买
                    if (has_bought) {
                        _detailType = typeBuyContinue;
                        BuyGoOnBottom *bbottom = [[[NSBundle mainBundle]loadNibNamed:@"BuyGoOnBottom" owner:self options:nil]lastObject];
                        bbottom.frame = CGRectMake(0, WYMHEIGHT - bbottom.frame.size.height, WYMWITH, bbottom.frame.size.height);
                        bbottom.car_model = car_model;
                        bbottom.father = self;
                        // _carImg.hidden = NO;
                        [self.view addSubview:bbottom];
                        
                        [bbottom setHidden:YES];
                        NSString *show_shopping = [[NSUserDefaults standardUserDefaults] valueForKey:@"show_shopping"];
                        if (show_shopping.integerValue == 1) {
                            [bbottom setHidden:NO];
                            _carImg.hidden = NO;
                        }
                        
                    }else{
                        _detailType = typeBuyNow;
                        BuyNowBottom *bbottom = [[[NSBundle mainBundle]loadNibNamed:@"BuyNowBottom" owner:self options:nil]lastObject];
                        bbottom.frame = CGRectMake(0, WYMHEIGHT - bbottom.frame.size.height, WYMWITH, bbottom.frame.size.height);
                        bbottom.car_model = car_model;
                        bbottom.father = self;
                        
                        [self.view addSubview:bbottom];
                        
                        [bbottom setHidden:YES];
                        NSString *show_shopping = [[NSUserDefaults standardUserDefaults] valueForKey:@"show_shopping"];
                        if (show_shopping.integerValue == 1) {
                            [bbottom setHidden:NO];
                            _carImg.hidden = NO;
                        }
                        
                    }
                }
                    break;
                case 3:
                {
                    if (has_bought) {
                        _detailType = typePublishedLogin;
                    }else{
                        _detailType = typePublished;
                    }
                    if (bottom == nil) {
                        bottom = [[[NSBundle mainBundle]loadNibNamed:@"GoToBottom" owner:self options:nil]lastObject];
                    }
                    if ([flagNum intValue] == 0) {
                        bottom.is_sold_out = NO;
                    }else{
                        bottom.is_sold_out = YES;
                    }
                    if ([qishu intValue]>=[maxqishu intValue]&&[qishu intValue]!=0) {
                        bottom.is_zuihou_flag = YES;
                    }else{
                        bottom.is_zuihou_flag = NO;
                    }
                    bottom.frame = CGRectMake(0, WYMHEIGHT - bottom.frame.size.height, WYMWITH, bottom.frame.size.height);
                    if (self.pdc_id!=nil) {
                        bottom.pdc_id = self.pdc_id;
                    }
                    [self.view addSubview:bottom];
                    [bottom setHidden:YES];
                    NSString *show_shopping = [[NSUserDefaults standardUserDefaults] valueForKey:@"show_shopping"];
                    if (show_shopping.integerValue == 1) {
                        [bottom setHidden:NO];
                    }
                    
                }
                    break;
                default:
                {
                    if (has_bought) {
                        _detailType = typeWaitPublishLogin;
                    }else{
                        _detailType = typeWaitPublish;
                    }
                    if (bottom == nil) {
                        bottom = [[[NSBundle mainBundle]loadNibNamed:@"GoToBottom" owner:self options:nil]lastObject];
                    }
                    
                    if ([flagNum intValue] == 0) {
                        bottom.is_sold_out = NO;
                    }else{
                        bottom.is_sold_out = YES;
                    }
                    if ([qishu intValue]>=[maxqishu intValue]&&[qishu intValue]!=0) {
                        bottom.is_zuihou_flag = YES;
                    }else{
                        bottom.is_zuihou_flag = NO;
                    }
                    bottom.frame = CGRectMake(0, WYMHEIGHT - bottom.frame.size.height, WYMWITH, bottom.frame.size.height);
                    if (self.pdc_id!=nil) {
                        bottom.pdc_id = self.pdc_id;
                    }
                    [self.view addSubview:bottom];
                    
                    [bottom setHidden:YES];
                    NSString *show_shopping = [[NSUserDefaults standardUserDefaults] valueForKey:@"show_shopping"];
                    if (show_shopping.integerValue == 1) {
                        [bottom setHidden:NO];
                    }
                    
                    
                }
                    break;
            }
            
            
            //表头
            _header = [[DetailHeader alloc]initWithType:_detailType andPics:pdc[@"goods"][@"picarr_url"]andDetailDic:pdc pdcId:self.pdc_id SID:pdc[@"goods"][@"sid"]];
            _header.pdc_id = self.pdc_id;
            
            //        NSLog(@"------->zf=%@",_header.father);
            _tableView.tableHeaderView = _header;
            [_tableView headerEndRefreshing];
            self.view.userInteractionEnabled = YES;
            
            [self requestForData];

        }

}
     
        failedBlock:^{
        self.view.userInteractionEnabled = YES;

        [WYPublic removeHudToWindow];
       [_tableView headerEndRefreshing];
    } needLog:NO];
}
//刷新表头
- (void)reloadTabHeaderWithDic:(NSDictionary *)dic
{
    
    NSDictionary *pdc = dic[@"data"];
    int has_bought = [pdc[@"has_bought"] intValue];
    NSNumber *status = pdc[@"status"];
    switch ([status intValue]) {
        case 1:
        {
            if (has_bought) {
                _detailType = typeBuyContinue;
            }else{
                _detailType = typeBuyNow;
            }
        }
            break;
        case 3:
        {
            if (has_bought) {
                _detailType = typePublishedLogin;
            }else{
                _detailType = typePublished;
            }
        }
            break;
        default:
        {
            if (has_bought) {
                _detailType = typeWaitPublishLogin;
            }else{
                _detailType = typeWaitPublish;
            }
        }
            break;
    }
    [_header reloadTabHeaderWithDic:pdc Type:_detailType];
    
    _tableView.tableHeaderView = _header;
}
//加载导航条
- (void)loadCustomNaviBar
{
    UIView *naviBar = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WYMWITH, 20+44)];
    naviBar.backgroundColor = QBB_RED_COLOR;
    //返回按钮
    PublicBackBtn *backBtn = [[PublicBackBtn alloc]initWithVC:self andBackType:pop Img:[UIImage imageNamed:@"icon_back_white_press"]];
    [naviBar addSubview:backBtn];
    //标题
    UILabel *titleLab = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 25)];
    titleLab.center = CGPointMake(WYMWITH/2, 42);
    titleLab.text = @"商品详情";
    titleLab.font = [UIFont systemFontOfSize:TITLE_SIZE];
    titleLab.textAlignment = NSTextAlignmentCenter;
    titleLab.textColor = [UIColor whiteColor];
    //分割线
    UILabel *fenge = [[UILabel alloc]initWithFrame:CGRectMake(0, 63.5, WYMWITH, 0.5)];
    fenge.backgroundColor = [UIColor lightGrayColor];
    [naviBar addSubview:fenge];
    [naviBar addSubview:titleLab];
    [self.view addSubview:naviBar];
    //购物车图标
    _carImg = [UIButton buttonWithType:0];
    _carImg.frame = CGRectMake(WYMWITH - 45, 28, 28, 28);
    [_carImg setImage:[UIImage imageNamed:@"icon_detail_buy_normal"] forState:UIControlStateNormal];
    [_carImg addTarget:self action:@selector(carbtnOnClick) forControlEvents:UIControlEventTouchUpInside];
    //添加圆角通知
    badgeView = [[JSBadgeView alloc] initWithParentView:_carImg alignment:JSBadgeViewAlignmentTopRight];
    [self updateTongZhi];
    badgeView.badgeBackgroundColor = [UIColor blackColor];
    _carImg.hidden = YES;
    badgeView.badgeBackgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"car_tz_bg"]];
    [naviBar addSubview:_carImg];
    
    NSString *show_shopping = [[NSUserDefaults standardUserDefaults] valueForKey:@"show_shopping"];
    [_carImg setHidden:YES];
    if (show_shopping.integerValue == 1) {
        [_carImg setHidden:NO];
    }

}
//购物车按钮的点击事件
- (void)carbtnOnClick
{
    //1.8
//    UIViewController *currentVC = [WYMainTabBarVC shareMainTaBarVC].selectedViewController;
//    [[WYMainTabBarVC shareMainTaBarVC].navigationController popToViewController:currentVC animated:NO];
    //1.8
    [self.navigationController popToRootViewControllerAnimated:YES];
    [[WYMainTabBarVC shareMainTaBarVC] changeSelectedWithIndex:2];;
}
//刷新圆角通知
- (void)updateTongZhi
{
    NSArray *pdcs = [[WYDataBase sharedDataBase]getAllpdcInCar];
    badgeView.badgeText = [NSString stringWithFormat:@"%ld",(unsigned long)pdcs.count];
    if (pdcs.count == 0) {
        badgeView.hidden = YES;
    }else{
        badgeView.hidden = NO;
    }
}
//加载表格
- (void)loadTableView
{
    CGFloat height = WYMHEIGHT - 64;
    NSString *show_shopping = [[NSUserDefaults standardUserDefaults] valueForKey:@"show_shopping"];
    if (show_shopping.integerValue == 1) {
        height -= 50;
    }

//    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, WYMWITH,  height)];
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, WYMWITH,  height) style:UITableViewStyleGrouped];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    //注册cell
    [_tableView registerNib:[UINib nibWithNibName:@"DetailCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    _tableView.rowHeight = 60.0;
    _tableView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"Dbb_backColor"]];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.tableFooterView = [[UIView alloc]init];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    //最后一页
    _footer = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, WYMWITH, 30)];
    _footer.text = @"已经是最后一页了";
    _footer.font = [UIFont systemFontOfSize:14];
    _footer.textColor = [UIColor grayColor];
    _footer.textAlignment = NSTextAlignmentCenter;
    _footer.backgroundColor = QBB_GRAY_COLOR;
    _footer.hidden = YES;
    _tableView.tableFooterView = _footer;
    [self.view addSubview:_tableView];
    
    
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    //    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    // dateKey用于存储刷新时间，可以保证不同界面拥有不同的刷新时间
    [_tableView addHeaderWithTarget:self action:@selector(headerRereshing) dateKey:@"table"];

    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [_tableView addFooterWithTarget:self action:@selector(footerRereshing)];
}
/**
 *  集成刷新控件
 */
- (void)headerRereshing
{
    _currentPage = 1;
    [_data removeAllObjects];
    [self requestForDetail];
}
- (void)footerRereshing
{
    _currentPage++;
    [self requestForData];
}
//加载参与记录
- (void)requestForData
{
    [WYPublic addHudToWindow];
    self.view.userInteractionEnabled = NO;
//    NSString *userFullStr = [WYPublic getUsefullStr:_goodsId];
    NSDictionary *params = @{@"id":[WYPublic getUsefullStr:_goodsId],@"num":@"10",@"page":[NSNumber numberWithInteger:_currentPage]};
    [WYRequest startPostForDicWithUrlStR:[NSString stringWithFormat:@"%@%@",DBB_IP,RECORD_URL] Parameters:params successBlock:^(NSDictionary *dic) {
        
        
        
        
        
        
        
        @synchronized(self) {
            NSString *ks_time = dic[@"data"][@"start_time"];
            if ([dic[@"data"][@"start_time"] class] != [NSNull class] ) {
                [_header updateTimelab:ks_time];
            }
            NSDictionary *records = dic[@"data"][@"list"];
            if (records.count > 0) {
                NSDictionary *records = dic[@"data"][@"list"];
                NSArray *keys = records.allKeys;
                // 利用block进行排序
                keys = [keys sortedArrayUsingComparator:
                        ^NSComparisonResult(NSString *obj1, NSString *obj2) {
                            // 先按照姓排序
                            NSComparisonResult result = [obj1  compare:obj2];
                            return result;
                        }];
                //倒叙
                keys = [[keys reverseObjectEnumerator] allObjects];
                for (NSString *key in keys) {
                    RecordModel *section = [[RecordModel alloc]init];
                    section.record_data = key;
                    if (_data.count>0) {
                        RecordModel *lastSection = _data[_data.count - 1];
                        if ([key isEqualToString:lastSection.record_data]) {
                            section = lastSection;
                            [_data removeObject:lastSection];
                        }
                    }
                    NSArray *re = records[key];
                    for (NSDictionary *record in re) {
                        
                        NSLog(@"record class: %@",[record class]);
//                        && ([record[@"addr"] isKindOfClass:[NSMutableDictionary class]
                        if([record class] != [NSNull class] && record != nil ){
                            
                            RecordModel *model = [[RecordModel alloc]init];
                            if (([record[@"addr"] class] != [NSNull class]) && (record[@"addr"] != nil  )) {
                                model.record_address = record[@"addr"];
                            }else{
                                model.record_address = @"地址待定";
                            }
                            model.record_data = record[@"date"];
                            model.record_id = record[@"id"];
                            model.record_img = record[@"img_url"];
                            model.record_ip = record[@"ip"];
                            model.record_name = record[@"username"];
                            model.record_sid = record[@"sid"];
                            model.record_time = record[@"time"];
                            model.record_totle = record[@"gonumber"];
                            model.record_uid = record[@"uid"];
                            model.record_data = record[@"date"];
                            if ([model.record_data isEqualToString:key]) {
                                [section.record_records addObject:model];
                            }

                        }
                    }
                    
                    [_data addObject:section];
                }
                _footer.hidden = YES;
            }else{
                _footer.hidden = NO;
            }
            [_tableView reloadData];
            [_tableView footerEndRefreshing];
            [WYPublic removeHudToWindow];
            self.view.userInteractionEnabled = YES;
            

        }

    }
        failedBlock:^{
            
        self.view.userInteractionEnabled = YES;

        [_tableView footerEndRefreshing];
        [WYPublic removeHudToWindow];
    } needLog:NO];
}


#pragma mark -- 表格协议函数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _data.count;
}
//cell header的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 40;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_data.count > 0) {
        RecordModel *sectionModel = _data[section];
        
        return sectionModel.record_records.count;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    DetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (_data.count>0) {
        RecordModel *sectionModel = _data[indexPath.section];
        RecordModel *rowModel = sectionModel.record_records[indexPath.row];
        [cell fillCellWithModel:rowModel];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    //获取段模型
    RecordModel *sectionModel = _data[section];
    UIView *header = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WYMWITH, 40)];
    header.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"Dbb_backColor"]];
    UILabel *timeLab = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 120, 22)];
    timeLab.center = CGPointMake(timeLab.frame.size.width/2+2, header.frame.size.height/2);
    timeLab.layer.borderWidth = 0.5f;
    timeLab.textColor = [UIColor grayColor];
    timeLab.textAlignment = NSTextAlignmentCenter;
    timeLab.layer.borderColor = [UIColor lightGrayColor].CGColor;
    timeLab.font = [UIFont systemFontOfSize:15.0];
    timeLab.text = sectionModel.record_data;
    UILabel *line_up = [[UILabel alloc]initWithFrame:CGRectMake(29.5, 0, 0.5, timeLab.frame.origin.y)];
    line_up.backgroundColor = [UIColor grayColor];
    [header addSubview:line_up];
    UILabel *line_down = [[UILabel alloc]initWithFrame:CGRectMake(29.5, CGRectGetMaxY(timeLab.frame), 0.5, header.frame.size.height - CGRectGetMaxY(timeLab.frame))];
    line_down.backgroundColor = [UIColor grayColor];
    [header addSubview:line_down];
    [header addSubview:timeLab];
    return header;
}

/*********解决段头跟随问题***************/
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView ==_tableView)
    {
        CGFloat sectionHeaderHeight = 60;
        if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0)
        {
            scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y,0, 0, 0);
        } else if (scrollView.contentOffset.y>=sectionHeaderHeight)
        {
            scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
        }
    }
}


- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
//    [WYPublic removeHudToWindow];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    self.view = nil;
}

-(void)dealloc{
    
    NSLog(@"PdcDetail dealloc");
}
@end
